package com.chinasofti.etc.alcohol.service.impl;

import com.chinasofti.etc.alcohol.dao.CommodityMapper;
import com.chinasofti.etc.alcohol.dao.model.Commodity;
import com.chinasofti.etc.alcohol.dao.model.CommodityCart;
import com.chinasofti.etc.alcohol.dao.CommodityCartMapper;
import com.chinasofti.etc.alcohol.exceptions.BusinessException;
import com.chinasofti.etc.alcohol.service.ICommodityCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinasofti.etc.alcohol.service.info.CartInfo;
import org.apache.groovy.util.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lucas
 * @since 2019-06-05
 */
@Service
public class CommodityCartServiceImpl extends ServiceImpl<CommodityCartMapper, CommodityCart> implements ICommodityCartService {

    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private CommodityCartMapper commodityCartMapper;

    @Override
    public void add(int commodityId, int count,int userId) {
        //是否已存在该记录，若存在更新数量，否则插入
        List<CommodityCart> commodityCarts = getBaseMapper().selectByMap(Maps.of("user_id", userId, "commodity_id", commodityId));
        if(commodityCarts==null||commodityCarts.isEmpty()){
            //根据id找到商品，生成购物车
            Commodity c = commodityMapper.selectById(commodityId);
            if(c==null){
                throw  new BusinessException("COMMODITY_NOT_FOUND","商品["+commodityId+"]未找到");
            }
            CommodityCart cart = new CommodityCart();
            cart.setCommodityName(c.getCommodityName());
            cart.setCommodityId(c.getCommodityId());
            cart.setNumber(count);
            cart.setCommodityMainImg(c.getCommodityImg());
            cart.setUserId(userId);
            getBaseMapper().insert(cart);

        }else{
            CommodityCart cart = commodityCarts.get(0);
            cart.setNumber(cart.getNumber()+count);
            getBaseMapper().updateById(cart);
        }
    }

    @Override
    public List<CartInfo> findAllCartItemByUserId(int userId) {

        List<CartInfo> allCartItemByUserId = getBaseMapper().findAllCartItemByUserId(userId);

        return allCartItemByUserId;
    }

}
